package com.ecodemo.everything;

import adrt.ADRTLogCatReader;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.core.content.FileProvider;
import java.io.File;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends Activity {
    private static final String[][] MIME_MapTable;//文件类型
    public static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);//线程池1
    public static ExecutorService fixedThreadPool2 = Executors.newSingleThreadExecutor();//线程池2
    static ArrayList<String> name = new ArrayList<>(); //文件名列表
    static ArrayList<File> resultl = new ArrayList<>();//文件列表
    int filn = 0;
    PkgCheck lista;
    ListView listv;
    TextView number;
    EditText rule;
    String rules = "";

    ArrayList<File> sl = new ArrayList<>();

    private class EarchThread implements Runnable {//数据更新线程
        private final File file;

        EarchThread(File file) {
            this.file = file;
        }

        @Override
        public void run() {
            resultl.add(file);
            name.add(file.getName());
        }
    }

	private class EarchThread2 implements Runnable {//递归查找线程
        private final File file;

        EarchThread2(File file) {
            this.file = file;
        }

        @Override
        public void run() {
            File[] listFiles = file.listFiles();
            for (File file : listFiles) {
                if (file.isDirectory()) {
					second(file);
                } else {
					add(file);
                }
            }
        }
    }

    private class EarchThread3 implements Runnable {//UI更新线程
        private final PkgCheck pc;
        private final int size;

        EarchThread3(int i, PkgCheck pc) {
            this.size = i;
            this.pc = pc;
        }

        @Override
        public void run() {
			number.setText(new StringBuffer().append("#").append(size).toString());
			listv.setAdapter(pc);
        }
    }

    static {
        String[][] file_type = new String[66][];//文件类型
        file_type[0] = new String[]{".3gp", "video/3gpp"};
        file_type[1] = new String[]{".apk", "application/vnd.android.package-archive"};
        file_type[2] = new String[]{".asf", "video/x-ms-asf"};
        file_type[3] = new String[]{".avi", "video/x-msvideo"};
        file_type[4] = new String[]{".bin", "application/octet-stream"};
        file_type[5] = new String[]{".bmp", "image/bmp"};
        file_type[6] = new String[]{".c", "text/plain"};
        file_type[7] = new String[]{".class", "application/octet-stream"};
        file_type[8] = new String[]{".conf", "text/plain"};
        file_type[9] = new String[]{".cpp", "text/plain"};
        file_type[10] = new String[]{".doc", "application/msword"};
        file_type[11] = new String[]{".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"};
        file_type[12] = new String[]{".xls", "application/vnd.ms-excel"};
        file_type[13] = new String[]{".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};
        file_type[14] = new String[]{".exe", "application/octet-stream"};
        file_type[15] = new String[]{".gif", "image/gif"};
        file_type[16] = new String[]{".gtar", "application/x-gtar"};
        file_type[17] = new String[]{".gz", "application/x-gzip"};
        file_type[18] = new String[]{".h", "text/plain"};
        file_type[19] = new String[]{".htm", "text/html"};
        file_type[20] = new String[]{".html", "text/html"};
        file_type[21] = new String[]{".jar", "application/java-archive"};
        file_type[22] = new String[]{".java", "text/plain"};
        file_type[23] = new String[]{".jpeg", "image/jpeg"};
        file_type[24] = new String[]{".jpg", "image/jpeg"};
        file_type[25] = new String[]{".js", "application/x-javascript"};
        file_type[26] = new String[]{".log", "text/plain"};
        file_type[27] = new String[]{".m3u", "audio/x-mpegurl"};
        file_type[28] = new String[]{".m4a", "audio/mp4a-latm"};
        file_type[29] = new String[]{".m4b", "audio/mp4a-latm"};
        file_type[30] = new String[]{".m4p", "audio/mp4a-latm"};
        file_type[31] = new String[]{".m4u", "video/vnd.mpegurl"};
        file_type[32] = new String[]{".m4v", "video/x-m4v"};
        file_type[33] = new String[]{".mov", "video/quicktime"};
        file_type[34] = new String[]{".mp2", "audio/x-mpeg"};
        file_type[35] = new String[]{".mp3", "audio/x-mpeg"};
        file_type[36] = new String[]{".mp4", "video/mp4"};
        file_type[37] = new String[]{".mpc", "application/vnd.mpohun.certificate"};
        file_type[38] = new String[]{".mpe", "video/mpeg"};
        file_type[39] = new String[]{".mpeg", "video/mpeg"};
        file_type[40] = new String[]{".mpg", "video/mpeg"};
        file_type[41] = new String[]{".mpg4", "video/mp4"};
        file_type[42] = new String[]{".mpga", "audio/mpeg"};
        file_type[43] = new String[]{".msg", "application/vnd.ms-outlook"};
        file_type[44] = new String[]{".ogg", "audio/ogg"};
        file_type[45] = new String[]{".pdf", "application/pdf"};
        file_type[46] = new String[]{".png", "image/png"};
        file_type[47] = new String[]{".pps", "application/vnd.ms-powerpoint"};
        file_type[48] = new String[]{".ppt", "application/vnd.ms-powerpoint"};
        file_type[49] = new String[]{".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"};
        file_type[50] = new String[]{".prop", "text/plain"};
        file_type[51] = new String[]{".rc", "text/plain"};
        file_type[52] = new String[]{".rmvb", "audio/x-pn-realaudio"};
        file_type[53] = new String[]{".rtf", "application/rtf"};
        file_type[54] = new String[]{".sh", "text/plain"};
        file_type[55] = new String[]{".tar", "application/x-tar"};
        file_type[56] = new String[]{".tgz", "application/x-compressed"};
        file_type[57] = new String[]{".txt", "text/plain"};
        file_type[58] = new String[]{".wav", "audio/x-wav"};
        file_type[59] = new String[]{".wma", "audio/x-ms-wma"};
        file_type[60] = new String[]{".wmv", "audio/x-ms-wmv"};
        file_type[61] = new String[]{".wps", "application/vnd.ms-works"};
        file_type[62] = new String[]{".xml", "text/plain"};
        file_type[63] = new String[]{".z", "application/x-compress"};
        file_type[64] = new String[]{".zip", "application/x-zip-compressed"};
        file_type[65] = new String[]{"", "*/*"};
        MIME_MapTable = file_type;
    }


    @Override
    protected void onResume() {
        super.onResume();
        this.rule.clearFocus();
    }

    @Override
    protected void onCreate(Bundle bundle) {
		ADRTLogCatReader.onContext(this, "com.aide.ui");
        super.onCreate(bundle);
        setContentView(R.layout.main);
        this.rule = findViewById(R.id.rule);
        this.listv = findViewById(R.id.listview);
        this.listv.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> adapterView, View view, int i, long j) {
					try {
						File file = new File(sl.get(i).getAbsolutePath());
						Intent intent = new Intent(Intent.ACTION_VIEW); 
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						//获取文件file的MIME类型 
						String type = getMIMEType(file); 
						//设置intent的data和Type属性
						Uri uri = null;
						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
							intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
							uri = FileProvider.getUriForFile(MainActivity.this, "com.ecodemo.everything.provider", file);
						} else {
							uri = Uri.fromFile(file);
						}
						intent.setDataAndType(uri, type);
						startActivity(intent);
					} catch (Exception ex) {
						Toast.makeText(getApplicationContext(), "找不到打开此文件的应用！", Toast.LENGTH_SHORT).show();
					}
				}
			});
        this.number = findViewById(R.id.number);
        resultl.clear();
        name.clear();
        getExtSDCardPath();//搜索sd卡里的数据
        second(Environment.getExternalStorageDirectory());//提前搜索好数据
        rule.addTextChangedListener(new TextWatcher() {
				@Override
				public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
				}

				@Override
				public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
				}

				@Override
				public void afterTextChanged(Editable editable) {
					if (editable.toString().length() > 0) {//长度不得小于0
						rules = editable.toString();
						doit();
					} else if (editable.toString().length() == 0) {
						sl.clear();
						show(new PkgCheck(MainActivity.this, R.layout.listlayout, (ArrayList)sl.clone()), sl.size());
					}
				}
			});
    }

    public void doit() { //清空总数并开始查找
        number.setText("#0");
        checkIsImageFile();//递归查找
    }

    void add(File file) {
        fixedThreadPool2.execute(new EarchThread(file));//将文件和文件名写入数组 单独线程
    }

    void second(File file) {
        fixedThreadPool.execute(new EarchThread2(file));//递归搜索文件线程
    }

    private void checkIsImageFile() {
        new Thread(new Runnable() {
				@Override
				public void run() {
					sl.clear();
					int size = resultl.size();
					for (int i = 0; i < size; i++) {
						try {
							if (new StringBuffer().append(name.get(i)).toString().contains(rules)) {
								sl.add(resultl.get(i));
							}
						} catch (IndexOutOfBoundsException e) {
						}
					}
					show(new PkgCheck(MainActivity.this, R.layout.listlayout, (ArrayList)sl.clone()), sl.size());
				}
			}).start();
    }

    void show(PkgCheck com_Delsart_search_pkgcheck, int i) { //更新UI
        runOnUiThread(new EarchThread3(i, com_Delsart_search_pkgcheck));
    }

    public void getExtSDCardPath() {//搜索SD卡里的数据
        fixedThreadPool.execute(new Runnable() {
				@Override
				public void run() {
					StorageManager storageManager = (StorageManager)getSystemService(Context.STORAGE_SERVICE);
					Class cls = null;
					try {
						cls = Class.forName("android.os.storage.StorageVolume");
						Method method = storageManager.getClass().getMethod("getVolumeList", new Class[0]);
						Method method2 = cls.getMethod("getPath", new Class[0]);//得到SD卡路径
						Method method3 = cls.getMethod("isRemovable", new Class[0]);
						Object invoke = method.invoke(storageManager, new Object[0]);
						int length = Array.getLength(invoke);
						for (int i = 0; i < length; i++) {
							Object obj = Array.get(invoke, i);
							String str = (String) method2.invoke(obj, new Object[0]);
							if (((Boolean) method3.invoke(obj, new Object[0])).booleanValue()) {
								second(new File(str));
							}
						}
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					} catch (InvocationTargetException e2) {
						e2.printStackTrace();
					} catch (NoSuchMethodException e3) {
						e3.printStackTrace();
					} catch (IllegalAccessException e4) {
						e4.printStackTrace();
					}
				}
			});
    }

    private static String getMIMEType(File file) {
        String str = "*/*";
        String name = file.getName();
        int lastIndexOf = name.lastIndexOf(".");
        if (lastIndexOf >= 0) {
            String toLowerCase = name.substring(lastIndexOf, name.length()).toLowerCase();
            if (toLowerCase != "") {
                for (int i = 0; i < MIME_MapTable.length; i++) {
                    if (toLowerCase.equals(MIME_MapTable[i][0])) {
                        str = MIME_MapTable[i][1];
                    }
                }
            }
        }
        return str;
    }
}

